<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .message {
        display: none;
      }
      .error ~ .message {
        display: inline;
      }
      .success {
        border: 2px solid greenyellow;
        outline: none;
      }
    </style>
  </head>
  <body>
    <h1>表单验证</h1>

    <form name="form">
      <p>
        用户 <input type="text" name="username" value="jack" />
        <span class="message">用户2-18位</span>
      </p>
      <p>
        邮箱 <input type="text" name="email" value="jack@qq.com" />
        <span class="message">邮箱格式错误</span>
      </p>
      <p>
        年龄 <input type="text" name="age" value="20" />
        <span class="message">年龄18-80之间</span>
      </p>
      <p>
        密码 <input type="password" name="password" value="123123" />
        <span class="message">密码必须6-18位</span>
      </p>
      <p>
        确认 <input type="password" name="password2" />
        <span class="message">两次密码输入不一致</span>
      </p>
      <p>
        <button type="button" name="submitBtn">提交</button>
      </p>
    </form>

    <script>
      const form = document.form;

      /*
      // rule参数类型：正则表达式，回调函数
      回调函数: 自定义验证规则
      */
      function valid(el, rule) {
        let r = false;
        // rule是正则表达式
        if (rule instanceof RegExp) {
          r = rule.test(el.value);
        }
        // rule是函数
        if (typeof rule === "function") {
          r = rule(el.value);
        }
        if (r) {
          el.classList.add("success");
          el.classList.remove("error");
        } else {
          el.classList.add("error");
          el.classList.remove("success");
        }
        return r;
      }

      form.submitBtn.onclick = function () {
        const r1 = valid(form.username, /^[a-z]{2,18}$/);
        const r2 = valid(form.email, /^\w+@\w+\.\w+$/);

        const r3 = valid(form.age, (value) => {
          return value >= 18 && value <= 80;
        });

        const r4 = valid(form.password, /^.{3,18}$/);

        const r5 = valid(form.password2, (value) => {
          return value === form.password.value;
        });

        if (r1 && r2 && r3 && r4) {
          console.log("success成功");
        }
      };
    </script>
  </body>
</html>
